//
//  HomeTableViewController.swift
//  weibo1
//
//  Created by 李进 on 15/10/14.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit
import SVProgressHUD

let HomeVCCellNormalId = "HomeVCCellNormalId"

let HomeVCCellRetweetId = "HomeVCCellRetweetId"

class HomeTableViewController: visitTableViewController {
    
    //定义一个数组来装
    private lazy var listViewModel = userFLViewModel()
    
    private lazy var showPhotoAnimator = ShowPhotoAnimator()

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        if userAccViewModel.shareAccViewModel.isLogin != true{
            
           visitview?.setupInfo("关注一些人，回这里看看有什么惊喜", homeImageName: nil)
            
            return
        }
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        prepareTableView()
        
        loaddta()
        
        //TODO: 自定义转场动画
        //接收点击图片cell的的通知//在通知中使用到self 一定会循环引用所以一定需要［weak self］
        NSNotificationCenter.defaultCenter().addObserverForName(sendNofotier, object: nil, queue: nil) { [weak self](notification) -> Void in
            //print(notification.userInfo)
            
            //这边判断是这样返回的数据类型就是对的
            guard let indexpaths = notification.userInfo?[CVStatusIndexPathKey] as? NSIndexPath else{
                print("没有点击cell")
                return
            }
            
            guard let urlss = notification.userInfo?[CVStatusURLsKey] as? [NSURL] else{
                return
            }
            
            
            let vc = showImageViewController(urls: urlss, indexpath: indexpaths)
            //这边也就是设置 modal 的方式是自定义形式
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            //设置转场动画的代理方法
            vc.transitioningDelegate = self?.showPhotoAnimator
            
        self?.presentViewController(vc, animated: true, completion: nil)
        }
        
        
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //懒加载上拉刷新的视图
    private lazy var actView: UIActivityIndicatorView = {
        
        let act = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        act.color = UIColor.lightGrayColor()
        
        return act
        
    }()
    
    /// 准备cell
    private func prepareTableView() {
        // 注册可重用 cell，原创
        tableView.registerClass(HomeVCNormalCell.self, forCellReuseIdentifier: HomeVCCellNormalId)
        //注册可重用cell 是转发微博的cell
        tableView.registerClass(HomeRetweetedCell.self, forCellReuseIdentifier: HomeVCCellRetweetId)
        
        // 自动计算行高 - 需要一个自上而下的自动布局的控件，指定一个向下的约束
        tableView.estimatedRowHeight = 400
       // tableView.rowHeight = 300
        
        //下拉刷新
        refreshControl = RefreshViewCV()
        
        refreshControl?.addTarget(self, action: "loaddta", forControlEvents: UIControlEvents.ValueChanged)
        
        //设置上拉刷新控件测试
        tableView.tableFooterView = actView
        
//        actView?.hidesWhenStopped = false
//        
//        actView?.startAnimating()
        
    }
    

    /// 加载数据方法
   @objc private func loaddta(){
    
        self.refreshControl?.beginRefreshing()
    
    listViewModel.loadUserFm(actView.isAnimating()) { (isSuccessed) -> () in
            
            //结束刷新
            self.refreshControl?.endRefreshing()
            
            if !isSuccessed {
                
                SVProgressHUD.showInfoWithStatus("加载数据错误，请稍后再试")
                return
            }
            
            //print(self.listViewModel.userFriendM.count)
            // 刷新数据
            self.tableView.reloadData()
        }
    }
    
//     deinit{
//        self.removeObserver(self, forKeyPath: "frame")
//    }
}


// MARK: - 实现数据源方法
extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //print(listViewModel.userFriendM.count)
        return listViewModel.userFriendM.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let vm = listViewModel.userFriendM[indexPath.row]
        
        
        let cell = tableView.dequeueReusableCellWithIdentifier(vm.cellId, forIndexPath: indexPath) as! HomeVCCell
        
        if indexPath.row == listViewModel.userFriendM.count - 1 {
            //如果是的话就开始动画
            actView.startAnimating()
            //并且刷新数据
            loaddta()
            
        }
        
        cell.viewModle = vm
        
        return cell
    }
    
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        //let vm = listViewModel.userFriendM[indexPath.item].rowHeight
        
//        if vm.rowHeight != nil {
//            return vm.rowHeight!
//        }
//
//        let cell = HomeVCCell(style: .Default, reuseIdentifier: HomeVCCellNormalId)
//        
//        vm.rowHeight = cell.rowHeight(vm)
        return listViewModel.userFriendM[indexPath.item].rowHeight!
    }
    

    
}